from flask import request, abort, jsonify
from . import todo_v1_bp
from ext import db
from app.models.models import TodoTask
from app.utils.utils import parse_date, parse_time


@todo_v1_bp.route('/tasks', methods=['GET'])
def get_tasks_list():
    """
    查看所有任务
    """
    tasks_list = TodoTask.query.all()
    return jsonify({"count": len(tasks_list), 'tasks': [tasks.to_json() for tasks in tasks_list]}), 200


@todo_v1_bp.route('/tasks/<int:id>', methods=['GET'])
def get_task(id):
    """
    查看单条任务
    """
    task = TodoTask.query.get_or_404(id)
    return jsonify(task.to_json()), 200


@todo_v1_bp.route('/tasks', methods=['POST'])
def create_task():
    """
    创建单条任务
    """
    if not request.json or 'name' not in request.json or 'assign' not in request.json:
        abort(400)

    new_todo = TodoTask()
    new_todo.name = request.json['name']
    new_todo.desc = request.json.get('desc', '')  # 获取描述字段，如果不存在则设置为空字符串
    new_todo.start_date = parse_date(request.json['start_date'])
    new_todo.start_time = parse_time(request.json['start_time'])
    new_todo.end_date = parse_date(request.json['end_date']) if 'end_date' in request.json else None
    new_todo.end_time = parse_time(request.json['end_time']) if 'end_time' in request.json else None
    new_todo.assign = request.json['assign']
    new_todo.status = request.json.get('status', 'INIT')  # 获取状态字段，如果不存在则设置为初始状态 'INIT'

    db.session.add(new_todo)
    db.session.commit()

    return jsonify({'task': new_todo.to_json()}), 201


@todo_v1_bp.route('/tasks/<int:id>', methods=['PUT'])
def update_task(id):
    """
    更新单条任务
    """
    if not request.json:
        abort(400)
    new_todo = TodoTask.query.get_or_404(id)
    # 任务名称
    if 'name' in request.json:
        new_todo.name = request.json['name']
    # 任务描述
    if 'desc' in request.json:
        new_todo.desc = request.json['desc']
    # 开始日期
    if 'start_date' in request.json:
        new_todo.start_date = request.json['start_date']
    # 开始时间
    if 'start_time' in request.json:
        new_todo.start_time = request.json['start_time']
    # 结束日期
    if 'end_date' in request.json:
        new_todo.end_date = request.json['end_date']
    # 结束时间
    if 'end_time' in request.json:
        new_todo.end_time = request.json['end_time']
    # 执行人
    if 'assign' in request.json:
        new_todo.assign = request.json['assign']
    # 状态
    if 'status' in request.json:
        new_todo.status = request.json['status']

    db.session.add(new_todo)
    db.session.commit()
    return jsonify({'task': new_todo.to_json()}), 201


@todo_v1_bp.route('/tasks/<int:id>', methods=['DELETE'])
def delete_task(id):
    """
    删除单条任务
    """
    todo = TodoTask.query.get_or_404(id)
    db.session.delete(todo)
    db.session.commit()
    return jsonify({'result': True}), 200
